package com.ptp.backendcertms.networksecurity.filter;

import com.alibaba.fastjson.JSON;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import javax.servlet.FilterConfig;
import java.util.*;

import static com.ptp.backendcertms.api.internal.constant.CertMsConstant.*;

/**
 * 基础过滤器
 *
 * @author songcongcong
 * @date 2025/5/3
 */
@Slf4j
public abstract class BaseFilter {
    private static final String FUZZY_MATCHING_REPLACE_SYMBOL = "*";

    /**
     * 获取处理或不处理的URL
     */
    protected List<String> getIncludeOrExcludeUrls(FilterConfig filterConfig, String paramKey) {
        String includePattern = filterConfig.getInitParameter(paramKey);
        if (StringUtils.isBlank(includePattern)) {
            return null;
        }
        return Arrays.asList(includePattern.split(ENGLISH_COMMA_SEPARATOR));
    }

    /**
     * 请求路径是否匹配
     */
    protected boolean servletPathIsMatching(List<String> urls, String servletPath) {
        return !CollectionUtils.isEmpty(urls) && urls.stream().anyMatch(t -> {
            if (t.contains(FUZZY_MATCHING_SYMBOL)) {
                return servletPath.startsWith(t.replace(FUZZY_MATCHING_REPLACE_SYMBOL, ""));
            }
            return servletPath.equals(t);
        });
    }

    /**
     * 对象转Map
     */
    protected Map<String, String[]> objectToMap(Object obj) {
        Map<String, Object> map = JSON.parseObject(JSON.toJSONString(obj), Map.class);
        Map<String, String[]> newMap = new HashMap<>(map.size());
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            newMap.put(entry.getKey(), new String[]{Objects.isNull(entry.getValue()) ? null : entry.getValue().toString()});
        }
        return newMap;
    }

}
